from numpy import *

# 构造一个简单数据集
def loadSimpData():
    datMat = matrix([[ 1. ,  2.1],
        [ 2. ,  1.1],
        [ 1.3,  1. ],
        [ 1. ,  1. ],
        [ 2. ,  1. ]])
    classLabels = [1.0, 1.0, -1.0, -1.0, 1.0]
    return datMat,classLabels

# 自适应数据加载函数，自动检测出特征的数目，默认最后一个特征为类别标签
def loadDataSet(fileName):      #general function to parse tab -delimited floats
    numFeat = len(open(fileName).readline().split('\t')) #get number of fields 
    dataMat = []; labelMat = []
    fr = open(fileName)
    for line in fr.readlines():
        lineArr =[]
        curLine = line.strip().split('\t')
        for i in range(numFeat-1):
            lineArr.append(float(curLine[i]))
        dataMat.append(lineArr)
        labelMat.append(float(curLine[-1]))
    return dataMat,labelMat


# 单层决策树生成函数
# 树桩分类函数，输入参数，数据集dataMatrix，维度dimen，阈值threshVal，不等号方向threshIneq
def stumpClassify(dataMatrix,dimen,threshVal,threshIneq):#just classify the data
    # 初始化分类数组，全部置1
    retArray = ones((shape(dataMatrix)[0],1))
    # 根据不等号的方向threshIneq，将在阈值一边的数据分到类别-1，而在另外一边的数据分到类别+1
    if threshIneq == 'lt':
        retArray[dataMatrix[:,dimen] <= threshVal] = -1.0
    else:
        retArray[dataMatrix[:,dimen] > threshVal] = -1.0
    return retArray    # 输出分类数组
# 构造一个树桩，输入参数，数据集dataArr，标签集classLabels，权重向量D
def buildStump(dataArr,classLabels,D):
    dataMatrix = mat(dataArr); labelMat = mat(classLabels).T
    # 获取数据集的样本数m和维度数n
    m,n = shape(dataMatrix)
    # 初始化步数numSteps、最优树桩bestStump、最优分类矩阵bestClasEst
    numSteps = 10.0; bestStump = {}; bestClasEst = mat(zeros((m,1)))
    minError = inf # 初始化minError为+∞
    for i in range(n): # 对数据集中的每一维特征（第一层循环）
        # 提取该维度特征的最大最小值
        rangeMin = dataMatrix[:,i].min(); rangeMax = dataMatrix[:,i].max();
        # 根据该维度特征的取值范围，设置步长stepSize
        stepSize = (rangeMax-rangeMin)/numSteps
        for j in range(-1,int(numSteps)+1): # 对当前特征维度下每一个步长（第二层循环）
            for inequal in ['lt', 'gt']: # 对每个不等号（第三层循环）
                # 计算分类阈值threshVal
                threshVal = (rangeMin + float(j) * stepSize)
                # 调用stumpClassify()函数进行分类预测
                predictedVals = stumpClassify(dataMatrix,i,threshVal,inequal)#call stump classify with i, j, lessThan
                # 构建一个错误向量errArr，如果预测值与真正类别标签值不一致则置1，否则置0
                errArr = mat(ones((m,1)))
                errArr[predictedVals == labelMat] = 0
                # 计算权重误差
                weightedError = D.T*errArr  #calc total error multiplied by D
                #print ("split: dim %d, thresh %.2f, thresh ineqal: %s, the weighted error is %.3f" % (i, threshVal, inequal, weightedError))
                # 如果权重误差小于最小误差，则更新最小误差minError、最优分类bestClasEst和最优树桩bestStump
                if weightedError < minError:
                    minError = weightedError
                    bestClasEst = predictedVals.copy()
                    bestStump['dim'] = i
                    bestStump['thresh'] = threshVal
                    bestStump['ineq'] = inequal
    return bestStump,minError,bestClasEst # 输出最优树桩、最小误差和最优分类

# 完整AdaBoost算法的实现
# 基于单层决策树的AdaBoost训练过程，输入参数，数据集dataArr，类别标签classLabels和迭代次数numIt
def adaBoostTrainDS(dataArr,classLabels,numIt=40):
    weakClassArr = []
    m = shape(dataArr)[0]   # 获取样本数m
    D = mat(ones((m,1))/m)  # 初始化列向量D
    aggClassEst = mat(zeros((m,1))) # 初始化列向量，记录每一个样本点的类别累计估计值
    for i in range(numIt):  # 循环运行numIt次，或者直到训练错误率为0为止
        # 建立一个单层决策树，该函数的输入为权重向量D，返回的则是利用D而得到的具有最小错误率的单层决策树，以及最小错误率和估计的类别向量 
        bestStump,error,classEst = buildStump(dataArr,classLabels,D) 
        #print ("D:",D.T)
        print ("bestStump:",bestStump)
        # 计算alpha值
        alpha = float(0.5*log((1.0-error)/max(error,1e-16))) # calc alpha, throw in max(error,eps) to account for error=0
        bestStump['alpha'] = alpha  
        weakClassArr.append(bestStump)                  #store Stump Params in Array
        #print ("classEst: ",classEst.T)
        # 计算下一次迭代中的新权重向量D
        expon = multiply(-1*alpha*mat(classLabels).T,classEst) #exponent for D calc, getting messy
        D = multiply(D,exp(expon))                              #Calc New D for next iteration
        D = D/D.sum()
        # 计算每一个样本的类别累计估计值aggClassEst
        aggClassEst += alpha*classEst
        #print ("aggClassEst: ",aggClassEst.T)
        # 计算整体训练样本类别标签预测的错误率errorRate
        aggErrors = multiply(sign(aggClassEst) != mat(classLabels).T,ones((m,1)))
        errorRate = aggErrors.sum()/m
        print ("total error: ",errorRate)
        if errorRate == 0.0: break  # 若训练错误率为0，则提前退出循环
    return weakClassArr,aggClassEst

# AdaBoost分类函数，输入参数，一个或多个待分类样例datToClass和多个弱分类器组成的弱分类器组classifierArr
def adaClassify(datToClass,classifierArr):
    dataMatrix = mat(datToClass)#do stuff similar to last aggClassEst in adaBoostTrainDS
    m = shape(dataMatrix)[0]
    aggClassEst = mat(zeros((m,1)))
    for i in range(len(classifierArr)):
        classEst = stumpClassify(dataMatrix,classifierArr[i]['dim'],\
                                 classifierArr[i]['thresh'],\
                                 classifierArr[i]['ineq'])#call stump classify
        aggClassEst += classifierArr[i]['alpha']*classEst
        #print (aggClassEst)
    return sign(aggClassEst)

# ROC曲线的绘制及AUC计算函数，输入参数，分类器预测强度predStrengths和分类标签classLabels
def plotROC(predStrengths, classLabels):
    import matplotlib.pyplot as plt
    cur = (1.0,1.0) # 初始化绘制光标的位置
    ySum = 0.0      # 初始化ySum，用于计算AUC值
    numPosClas = sum(array(classLabels)==1.0)   # 计算正样例个数numPosClas
    # 确定坐标轴上的步长
    yStep = 1/float(numPosClas); xStep = 1/float(len(classLabels)-numPosClas)
    # 获取排序索引
    sortedIndicies = predStrengths.argsort()#get sorted index, it's reverse
    # 构建画笔
    fig = plt.figure()
    fig.clf()
    ax = plt.subplot(111)
    # 当循环遍历表时，没得到一个标签为+1类时，则沿着y轴的方向下降一个步长，即不断降低真阳率；
    # 类似地，对于每个其他类型的标签，则沿着x轴的方向倒退一个步长，即不断降低假阳率。
    for index in sortedIndicies.tolist()[0]:
        if classLabels[index] == 1.0:
            delX = 0; delY = yStep;
        else:
            delX = xStep; delY = 0;
            ySum += cur[1]
        #draw line from cur to (cur[0]-delX,cur[1]-delY)
        ax.plot([cur[0],cur[0]-delX],[cur[1],cur[1]-delY], c='b')
        cur = (cur[0]-delX,cur[1]-delY)
    ax.plot([0,1],[0,1],'b--')
    plt.xlabel('False positive rate'); plt.ylabel('True positive rate')
    plt.title('ROC curve for AdaBoost horse colic detection system')
    ax.axis([0,1,0,1])
    plt.show()
    print ("AUC(the Area Under the Curve): ",ySum*xStep)
